const api = require('../../../api/mop_api');
import { toast, log, err } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    item: {},
    show: false,
    page: 1,
    size: 20,
    pageTotal: 0,
    cha: '',
  },
  onLoad() {
    this.vipList();
  },

  async vipList() {
    try {
      const { page, size } = this.data;
      const res = await api.viplist({ page, size });
      if (res.respCode === 200) {
        const list = JSON.parse(res.source);
        if (this.data.list.length === 0) {
          this.setData({
            list,
            pageTotal: res.pageTotal,
          });
        } else {
          this.setData({
            list: this.data.list.concat(list),
            pageTotal: res.pageTotal,
          });
        }
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  vipDtl(e) {
    const { item } = e.currentTarget.dataset;
    this.setData({
      item,
      show: true,
    });
    this.del(item.id);
  },
  async del(e) {
    try {
      const res = await api.vipget({ id: e });
      if (res.respCode === 200) {
        const item = JSON.parse(res.source);
        log(item);
        this.setData({ item });
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  give() {
    try {
      wx.showModal({
        title: '请输入充值积分金额',
        editable: true,
        complete: async res => {
          console.log(res);
          if (res.confirm) {
            if (!res.content) return toast('请输入充值积分金额');
            if (isNaN(res.content)) return toast('请输入数字');
            const data = {
              memberId: this.data.item.id,
              payType: 'POINT_RECHARGE',
              amount: res.content,
            };
            const ress = await api.give_points(data);
            if (ress.respCode === 200) {
              this.del(this.data.item.id);
              toast('充值成功');
            } else {
              toast(ress.msg);
            }
          }
        },
      });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  onClose() {
    this.setData({ show: false });
  },
  search(e) {
    const { show, item } = e.detail;
    this.setData({ show, item });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let { list, pageTotal, page } = this.data;
    if (list.length < pageTotal) {
      this.setData({ page: page + 1 });
      this.vipList();
    } else {
      toast('已加载全部数据');
    }
  },
});
